<template>
	<van-form>
	  <van-cell-group inset>
		<van-field
		  v-model="formData.time"
		  readonly
		  name="time"
		  label="时间:"
		  placeholder="点击选择时间"
		  @click="showPicker = true"
		>
			<template #input>
				<ifun-date-picker 
					type="date" 
					:value="pickerValue" 
					:gap="[[2015],[2055]]" 
					@ok="onConfirm"
					@cancel="onCancel">
				</ifun-date-picker>
			</template>
		</van-field>
		<van-field
		  :colon="true"
		  v-for="item in formClom"
		  :key="item.key"
		  v-model="formData[item.key]"
		  :name="item.key"
		  :label="item.label"
		  :rules="[{ required: true,message: '请输入数字!' }]"
		>
			<template #input>
				<u--input type="number" :placeholder="item.label" v-model="formData[item.key]"></u--input>
			</template>
			<template #button>
			  <text>元</text>
			</template>
		</van-field>
	  </van-cell-group>
	  <view style="margin: 16px;margin-bottom: 10px;">
		<van-button block type="success" native-type="submit"  @click="onSubmit">
		  添加
		</van-button>
	  </view>
	  <up-toast ref="uToastRef"></up-toast>
	</van-form>
</template>

<script setup>
import { ref, reactive } from 'vue';
import { precisionCalc, setLocalData } from '@/utils/util'
import { defaultData, formClom } from '@/utils/config.js'
// #ifdef APP || APP-ANDROID
// 组件丢失问题处理
import UpToast from '@/uni_modules/uview-plus/components/u-toast/u-toast.vue'
// #endif

const showDialog = ref(false)
const showPicker = ref(false)
const uToastRef = ref(null)
const pickerValue = ref()
const formData = reactive(Object.assign({}, defaultData))



const onConfirm = (selectedValues) => {
	setFormData(defaultData)
	pickerValue.value = selectedValues;
	formData.time = selectedValues
	showPicker.value = false;
};

const onCancel = () => showPicker = false
const onSubmit = () => {
	// setPicData([
	// 	"支付方式汇总",
	// 	"实收金额",
	// 	"抖音券支付",
	// 	"97",
	// 	"支付宝",
	// 	"226.6",
	// 	"美团券支付",
	// 	"390",
	// 	"微信",
	// 	"5053.3",
	// 	"现金支付",
	// 	"1819.4",
	// 	"余额",
	// 	"848.77",
	// 	"小计",
	// 	"8435.07",
	// 	"会员消费统计",
	// 	"储值消费笔数:6",
	// 	"储值消费总额:848.77"
	// ])
	// console.log(formData);
	setLocalData(formData).then( res => {
		uToastRef.value.show({
			type: "success",
			title: "完成",
			message: "保存成功",
			complete() {
				uni.navigateTo({
					url: '/',
				});
			},
		})
	}).catch( err => {
		uToastRef.value.show({
			type: "error",
			title: "提示",
			message: err
		})
	})
}

const setFormData = (data) => {
	for (let key in data) {
		if (formData.hasOwnProperty(key)) {
			formData[key] = data[key];
		}
	}
}

const setPicData = (arr) => {
	const obj = JSON.parse(JSON.stringify(defaultData))
	delete obj.time
	setFormData(obj)
	formClom.forEach(item => {
		const index = arr.findIndex(i => i === item.label)
		if(index !== -1) formData[item.key] = arr[index + 1]
	})
}
	
defineExpose({
	setFormData,
	setPicData
})
</script>

<style>
.u-input.u-border{
	padding: 0 !important;
	border: none !important;
}
</style>